import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../utils/router_helper.dart';
import '../../../../utils/string_utils.dart';
import '../../../../utils/common_req_utils.dart';
import '../../../../widget/label_item.dart';
import '../../../../widget/w_toast.dart';

class DriveFeedBackUpdatePage extends StatefulWidget {
  int feedbackId;

  DriveFeedBackUpdatePage({super.key, required this.feedbackId});

  @override
  BaseState<DriveFeedBackUpdatePage> createState() =>
      _DriveFeedBackUpdatePageState();
}

class _DriveFeedBackUpdatePageState extends BaseState<DriveFeedBackUpdatePage> {
  final _formKey = GlobalKey<FormState>();
  List<Map> driveStatus =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.driveStatus);
  List<Map> modelList = WConstant.modelList;
  List<Map> saleManList=WConstant().salesmanList;

  Map driveFeedBackDetail = {};

  GlobalKey<LabelItemState>? driveExperienceKey;
  GlobalKey<LabelItemState>? modelKey;

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "试驾回访",
        resizeToBottomInset: true,
        child: Column(children: [
          Expanded(
              child: SingleChildScrollView(
            padding: EdgeInsets.zero,
            child: _bookDriveItem(),
          )),
          GestureDetector(
            onTap: () {
              if (StringUtils.safeGetValue(driveFeedBackDetail["probeTime"]) ==
                  "") {
                Toast.toast("请填写回访时间");
                return;
              }
              if (StringUtils.safeGetValue(
                      driveFeedBackDetail["driveExperience"]) ==
                  "") {
                Toast.toast("请填写试驾体验");
                return;
              }
              CommonUtils.throttle(save);
            },
            child: Container(
              margin: EdgeInsets.symmetric(vertical: 16.px, horizontal: 10.px),
              width: SizeUtils.screenW() - 48.px,
              alignment: Alignment.center,
              height: 48.px,
              decoration: BoxDecoration(
                color: WColors.primaryColor,
                borderRadius: BorderRadius.circular(24.px),
              ),
              child: WText(
                "保存",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.px,
                ),
              ),
            ),
          ),
        ]));
  }

  void save() {
    showLoading();
    driveFeedBackDetail["id"] = widget.feedbackId;
    String selectedTime = driveFeedBackDetail["probeTime"] + ":00";
    DateTime selected = DateTime.parse(selectedTime);
    bool isAfter = DateTime.now().isBefore(selected);
    if (isAfter) {
      Toast.toast("回访时间不能大于当前时间");
      return;
    }
    Map<String, dynamic> dataMap = {
      "id": widget.feedbackId,
      "probeTime": driveFeedBackDetail["probeTime"] + ":00",
      "driveExperience": driveFeedBackDetail["driveExperience"],
      "isProbe":"10041001",
      "status": driveFeedBackDetail["status"],
      "salesService": double.parse(StringUtils.safeGetValue(driveFeedBackDetail["salesService"],placeHolder: "0.0")).toInt(),
      "testDriveExperience":double.parse(StringUtils.safeGetValue(driveFeedBackDetail["testDriveExperience"],placeHolder: "0.0")).toInt(),
    };
    print(dataMap);
    HttpUtils()
        .post(Api.saveTestDriveFeedBackInfo, data: dataMap)
        .then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        Toast.toast("回访成功");
        RouteHelper.maybePop(context, true);
      } else {
        Toast.toast(value.errMsg ?? "");
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  Widget _bookDriveItem() {
    return Form(
        key: _formKey,
        child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(
                left: 10.px, right: 10.px, bottom: 10.px, top: 10.px),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                      //线框阴影线条
                      color: WColors.border,
                      offset: Offset(0, 1),
                      blurRadius: 2)
                ]),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  LabelItem(
                    label: "客户名称",
                    value: driveFeedBackDetail["customerName"],
                  ),
                  LabelItem(
                    label: "手机号码",
                    value: driveFeedBackDetail["phone"],
                  ),
                  LabelItem(
                      label: "试驾类型",
                      isMust: true,
                 //     labelType: LabelType.TEXT,
                      value: StringUtils.safeGetValue(
                          driveFeedBackDetail["driveTypeName"])),
                  LabelItem(
                      label: "试驾方式",
                      isMust: true,
                    //  labelType: LabelType.TEXT,
                      value: StringUtils.safeGetValue(
                          driveFeedBackDetail["driveMethodName"])),
                  // LabelItem(
                  //   label: "试驾车型",
                  //   key: modelKey,
                  //   isMust: true,
                  //   labelType: LabelType.DROW_DOWN,
                  //   dataList: modelList,
                  //   value: StringUtils.safeGetValue(
                  //       driveFeedBackDetail["modelId"]),
                  // ),
                  LabelItem(
                    isMust: true,
                    label: "试驾车型",
                    value: CommonReqUtils.exchangeCodeToName2(
                        modelList, driveFeedBackDetail["modelId"]),
                  ),
                  LabelItem(
                    label: "开始时间",
                    value: driveFeedBackDetail["startDriveTime"] ?? "-",
                  ),
                  LabelItem(
                    label: "结束时间",
                    value: driveFeedBackDetail["endDriveTime"] ?? "-",
                  ),
                  LabelItem(
                    label: "接待顾问",
                    value: StringUtils.safeGetValue(driveFeedBackDetail["saleMan"],
                        placeHolder: "-"),
                  ),
                  LabelItem(
                      label: "试驾状态",
                      isMust: true,
                    //  labelType: LabelType.TEXT,
                      value: StringUtils.safeGetValue(
                          driveFeedBackDetail["statusName"])),
                  LabelItem(
                    isMust: true,
                    labelType: LabelType.DATETIME,
                    label: "回访时间",
                    minDateTime: DateTime(1970, 1, 1),
                    maxDateTime: DateTime.now(),
                    onDateChanged: (text) {
                      setState(() {
                        driveFeedBackDetail["probeTime"] = text;
                      });
                    },
                    value: driveFeedBackDetail["probeTime"] ?? "",
                  ),

                  LabelItem(
                    labelType: LabelType.RATINGBAR,
                    label: "试驾体验",
                    isMust: true,
                    value: StringUtils.safeGetValue(driveFeedBackDetail["testDriveExperience"]),
                    onSelected: (text) {
                      setState(() {
                        driveFeedBackDetail["testDriveExperience"] = text;
                      });
                    },
                  ),
                  LabelItem(
                    labelType: LabelType.RATINGBAR,
                    label: "销售服务",
                    isMust: true,
                    value: StringUtils.safeGetValue(driveFeedBackDetail["salesService"]),
                    onSelected: (text) {
                      setState(() {
                        driveFeedBackDetail["salesService"] = text;
                      });
                    },
                  ),
                  LabelItem(
                    key: driveExperienceKey,
                    labelType: LabelType.TEXTAREA,
                    label: "试驾评价",
                    isMust: true,
                    value: driveFeedBackDetail["driveExperience"],
                    maxTextLength: 500,
                    onChanged: (text) {
                      setState(() {
                        driveFeedBackDetail["driveExperience"] = text;
                      });
                    },
                  ),
                ])));
  }

  void _printFormData() {
    print('编辑保存的对象是: $driveFeedBackDetail');

    // 如果需要，你可以在这里添加提交表单的逻辑，例如通过网络请求发送数据到服务器
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    driveExperienceKey = GlobalKey(debugLabel: "driveExperience");
    modelKey = GlobalKey(debugLabel: "modelKey");
    showLoading();
    HttpUtils()
        .get("${Api.getTestDriveDetail}/${widget.feedbackId}")
        .then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        print("试驾回访详情查询返回结果");
        print(data.data);
        driveFeedBackDetail = data.data;
        driveFeedBackDetail["driveTypeName"] =
            CommonReqUtils.exchangeCodeToName(CommonReqUtils.driveType,
                StringUtils.safeGetValue(driveFeedBackDetail["driveType"]));
        driveFeedBackDetail["driveMethodName"] =
            CommonReqUtils.exchangeCodeToName(CommonReqUtils.driveMethod,
                StringUtils.safeGetValue(driveFeedBackDetail["driveMethod"]));
        driveFeedBackDetail["statusName"] = CommonReqUtils.exchangeCodeToName(
            CommonReqUtils.driveStatus,
            StringUtils.safeGetValue(driveFeedBackDetail["status"]));
        setState(() {});
        driveExperienceKey!.currentState
            ?.refreshInput(driveFeedBackDetail["driveExperience"] ?? "");
        modelKey!.currentState
            ?.refreshList(modelList, driveFeedBackDetail["modelId"]);
      } else if (data.resultCode == 500) {
        Toast.toast(data.errMsg ?? "");
      }
    });
  }
}
